package android.fwirk;

import org.json.JSONObject;
import com.google.jplurk.PlurkClient;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;

import android.fwirk.obj.CustomProgressDialog;
import android.fwirk.plurk.PlurkCustomClient;
import android.fwirk.plurk.PlurkUser;
import android.fwirk.twitter.TwitterClient;
import android.fwirk.twitter.TwitterUser;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

public class LoginActivity extends Activity implements OnClickListener,
		android.content.DialogInterface.OnClickListener, OnKeyListener {
	Button logIn;
	EditText twitterUsername;
	EditText twitterPassword;
	EditText plurkUsername;
	EditText plurkPassword;
	Intent intent;
	int tID = 0;
	boolean canFacebook = false;
	boolean canTwitter = false;
	boolean canPlurk = false;
	boolean willFacebook = false;
	boolean willTwitter = false;
	boolean willPlurk = false;
	boolean hasPerm = false;

	Bundle b;
	Builder builder;
	AlertDialog alert;
	ImageView pTwitterImg;
	CustomProgressDialog progress;
	AlertDialog about;

	private final int MENU_ABOUT = 0;
	private final int DIALOG_PROGRESS = 0;
	private final int DIALOG_ABOUT = 1;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.login2);
		Bundle extra = getIntent().getExtras();
		willFacebook = extra.getBoolean("willFacebook", false);
		logIn = (Button) findViewById(R.id.signb);
		logIn.setOnClickListener(this);
		twitterUsername = (EditText) findViewById(R.id.twitterUsername);
		twitterPassword = (EditText) findViewById(R.id.twitterPassword);
		plurkUsername = (EditText) findViewById(R.id.plurkUsername);
		plurkPassword = (EditText) findViewById(R.id.plurkPassword);
		plurkUsername.setOnKeyListener(this);
		plurkPassword.setOnKeyListener(this);
		twitterUsername.setOnKeyListener(this);
		twitterPassword.setOnKeyListener(this);
		pTwitterImg = (ImageView) findViewById(R.id.pTwitterImg);
		pTwitterImg.setOnClickListener(this);
		intent = new Intent(this, StartupActivity.class);
		builder = new Builder(this);
		builder.setCancelable(false);
		builder.setPositiveButton("Yes", this).setNegativeButton("No", this);
		progress = new CustomProgressDialog(this);
	}

	@Override
	protected Dialog onCreateDialog(int id) {
		if (id == DIALOG_PROGRESS) {
			return progress.getDialog();
		} else if (id == DIALOG_ABOUT) {
			Builder bhelp = new Builder(this);
			bhelp
					.setMessage(
							"fwirk\n\nA Facebook, Twitter and Plurk status updater on the Android platform\n\nCredits to:\nMel Leandro Navarro 2006-03375\nReynaldo Manguni\n\n")
					.setPositiveButton("Back",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int which) {
									dialog.dismiss();

								}
							});
			return bhelp.create();
		}
		return super.onCreateDialog(id);
	}

	public void onClick(View v) {
		if (v == logIn) {
			boolean status = true;
			canFacebook = false;
			canTwitter = false;
			canPlurk = false;
			willTwitter = false;
			willPlurk = false;
			hasPerm = false;
			progress.setText("Signing in...");
			progress.setImage1(R.drawable.facebookd);
			progress.setImage2(R.drawable.twitterd);
			progress.setImage3(R.drawable.plurkd);
			progress.setPBarVisibility(View.VISIBLE);
			progress.setImage1Visibility(View.GONE);
			progress.setImage2Visibility(View.GONE);
			progress.setImage3Visibility(View.GONE);

			if (twitterUsername.getText().length() > 0
					&& twitterPassword.getText().length() == 0) {
				Toast.makeText(this, "Please fill in Twitter password",
						Toast.LENGTH_SHORT).show();
				status = false;
			} else if (twitterUsername.getText().length() == 0
					&& twitterPassword.getText().length() > 0) {
				Toast.makeText(this, "Please fill in Twitter username",
						Toast.LENGTH_SHORT).show();
				status = false;
			}
			if (plurkUsername.getText().length() > 0
					&& plurkPassword.getText().length() == 0) {
				Toast.makeText(this, "Please fill in Plurk password",
						Toast.LENGTH_SHORT).show();
				status = false;
			} else if (plurkUsername.getText().length() == 0
					&& plurkPassword.getText().length() > 0) {
				Toast.makeText(this, "Please fill in Plurk username",
						Toast.LENGTH_SHORT).show();
				status = false;
			}
			if (status && !willFacebook
					&& twitterUsername.getText().length() == 0
					&& plurkUsername.getText().length() == 0) {
				Toast.makeText(this,
						"Please fill in at least one sign-in info",
						Toast.LENGTH_SHORT).show();
				status = false;
			}
			if (status) {
				intent = new Intent(this, StartupActivity.class);
				if (willFacebook) {
					progress.setImage1Visibility(View.VISIBLE);
				}
				if (twitterUsername.getText().length() > 0) {
					willTwitter = true;
					progress.setImage2Visibility(View.VISIBLE);
				}
				if (plurkUsername.getText().length() > 0) {
					willPlurk = true;
					progress.setImage3Visibility(View.VISIBLE);
				}
				tID++;
				showDialog(DIALOG_PROGRESS);
				LoginThread ft = null;
				LoginThread tt = null;
				LoginThread pt = null;
				Const.yfrog.setUsername(Const.TWITPIC_USER);
				Const.yfrog.setPassword(Const.TWITPIC_PASS);
				if (willFacebook) {
					ft = new LoginThread(this, loginH, "", null,
							Const.TYPE_FACEBOOK, tID % Integer.MAX_VALUE);
					ft.start();
				}
				if (willTwitter) {
					tt = new LoginThread(this, loginH, twitterUsername
							.getText().toString(), twitterPassword.getText()
							.toString(), Const.TYPE_TWITTER, tID
							% Integer.MAX_VALUE);
					tt.start();
				}
				if (willPlurk) {
					pt = new LoginThread(this, loginH, plurkUsername.getText()
							.toString(), plurkPassword.getText().toString(),
							Const.TYPE_PLURK, tID % Integer.MAX_VALUE);
					pt.start();
				}
				WaitThread wt = new WaitThread(waitLoginH, ft, tt, pt, tID
						% Integer.MAX_VALUE);
				wt.start();
			}
		} else if (v == pTwitterImg) {
			pTwitterImg.setSelected(!pTwitterImg.isSelected());
			if (pTwitterImg.isSelected()) {
				plurkUsername.setText(twitterUsername.getText());
				plurkPassword.setText(twitterPassword.getText());
				plurkUsername.setEnabled(false);
				plurkPassword.setEnabled(false);
			} else {
				plurkUsername.setText("");
				plurkPassword.setText("");
				plurkUsername.setEnabled(true);
				plurkPassword.setEnabled(true);
			}
		}
	}

	public void onClick(DialogInterface arg0, int arg1) {
		if (arg0 == alert) {
			switch (arg1) {
			case DialogInterface.BUTTON_POSITIVE:
				String m;
				m = "You are now signed in ";
				if (canFacebook) {
					m = m + "Facebook";
				}
				if (canTwitter) {
					if (canFacebook) {
						m = m + ",";
					}
					m = m + "Twitter";
				}
				if (canPlurk) {
					if (canTwitter || canFacebook) {
						m = m + ",";
					}
					m = m + "Plurk";
				}
				Toast.makeText(getApplicationContext(), m, Toast.LENGTH_SHORT)
						.show();
				startActivity(intent);
				break;
			case DialogInterface.BUTTON_NEGATIVE:
				alert.dismiss();
				break;
			}
		}

	}

	public boolean onKey(View arg0, int arg1, KeyEvent arg2) {
		if (arg0 == twitterUsername) {
			if (pTwitterImg.isSelected()) {
				plurkUsername.setText(twitterUsername.getText());
			}
		} else if (arg0 == twitterPassword) {
			if (pTwitterImg.isSelected()) {
				plurkPassword.setText(twitterPassword.getText());
			}
		}
		return false;
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		menu.add(0, MENU_ABOUT, 0, "About").setIcon(
				android.R.drawable.ic_menu_help);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case MENU_ABOUT:
			showDialog(DIALOG_ABOUT);
			break;
		}
		return true;
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			if (progress.isShowing()) {
				progress.hide();
			}
		}
		return super.onKeyDown(keyCode, event);
	}

	final Handler loginH = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			if (msg.getData().getInt("tID") == tID % Integer.MAX_VALUE) {
				if (msg.getData().getBoolean("status")
						&& msg.getData().getInt("type") == Const.TYPE_FACEBOOK) {
					canFacebook = true;
					progress.setImage1(R.drawable.facebooke);

				} else if (msg.getData().getBoolean("status")
						&& msg.getData().getInt("type") == Const.TYPE_TWITTER) {
					canTwitter = true;
					progress.setImage2(R.drawable.twittere);

				} else if (msg.getData().getBoolean("status")
						&& msg.getData().getInt("type") == Const.TYPE_PLURK) {
					canPlurk = true;
					progress.setImage3(R.drawable.plurke);
				}
			}
		}
	};

	final Handler waitLoginH = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			if (msg.getData().getInt("tID") == tID % Integer.MAX_VALUE) {
				progress.hide();
				if (!canFacebook && !canTwitter && !canPlurk) {
					Toast
							.makeText(
									getApplicationContext(),
									"Please check usernames/passwords, could not connect to any of the services.",
									Toast.LENGTH_SHORT).show();
				} else {
					String m = "Could not sign in with ";
					if (willFacebook && !canFacebook) {
						m = m + "Facebook";
					}
					if (willTwitter && !canTwitter) {
						if (willFacebook && !canFacebook) {
							m = m + ",";
						}
						m = m + "Twitter";
					}
					if (willPlurk && !canPlurk) {
						if ((willTwitter && !canTwitter)
								|| (willFacebook && !canFacebook)) {
							m = m + ",";
						}
						m = m + "Plurk";
					}
					m = m + " credentials. Continue logging in?";
					b = new Bundle();
					b.putBoolean("canFacebook", canFacebook);
					b.putBoolean("canPlurk", canPlurk);
					b.putBoolean("canTwitter", canTwitter);
					intent.putExtras(b);
					if ((willFacebook && !canFacebook)
							|| (willTwitter && !canTwitter)
							|| (willPlurk && !canPlurk)) {
						alert = builder.setMessage(m).show();
					} else {
						m = "You are now signed in ";
						if (canFacebook) {
							m = m + "Facebook";
						}
						if (canTwitter) {
							if (canFacebook) {
								m = m + ",";
							}
							m = m + "Twitter";
						}
						if (canPlurk) {
							if (canTwitter || canFacebook) {
								m = m + ",";
							}
							m = m + "Plurk";
						}
						Toast.makeText(getApplicationContext(), m,
								Toast.LENGTH_SHORT).show();
						startActivity(intent);
						setResult(Activity.RESULT_OK);
						finish();
					}
				}
			}
		}
	};

}

class LoginThread extends Thread {
	Handler mHandler;
	boolean status;
	String username;
	String password;
	int tID;
	int type;
	Context context;

	public LoginThread(Context context, Handler mHandler, String username,
			String password, int type, int tID) {
		this.mHandler = mHandler;
		this.username = username;
		this.password = password;
		this.tID = tID;
		this.type = type;
		this.context = context;
	}

	@Override
	public void run() {
		status = false;
		if (type == Const.TYPE_FACEBOOK) {
			try {
				Const.facebook.getSession(Const.facebookToken);
				if(Const.facebook.isPermitted()) {
					status = true;
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		} else if (type == Const.TYPE_TWITTER) {
			Log.d("Test", "twitter login ");
			Const.twitter = new TwitterClient(new TwitterFactory().getInstance(username, password));
			try {
				Const.twitter.setUser(new TwitterUser(Const.twitter.verifyCredentials()));
				Const.yfrog.setUsername(username);
				Const.yfrog.setPassword(password);
				Log.d("Test", "twitter logged in");
				status = true;
			} catch (TwitterException e) {
				e.printStackTrace();
			}
		} else if (type == Const.TYPE_PLURK) {
			status = false;
			Const.plurk = new PlurkCustomClient(new PlurkClient(
					Const.plurkSettings));
			try {
				Log.d("Test", "plurk login ");
				JSONObject user = Const.plurk.login(username, password);
				if (user.isNull("error_text")) {
					Const.plurk.setUser(new PlurkUser(user));
					Log.d("Test", "plurk logged in");
					status = true;
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		Message m = mHandler.obtainMessage();
		Bundle b = new Bundle();
		b.putInt("type", type);
		b.putBoolean("status", status);
		b.putInt("tID", tID);
		m.setData(b);
		mHandler.sendMessage(m);
	}
}

class WaitThread extends Thread {
	Handler mHandler;
	Thread ft;
	Thread tt;
	Thread pt;
	int tID;

	public WaitThread(Handler mHandler, Thread ft, Thread tt, Thread pt, int tID) {
		this.mHandler = mHandler;
		this.ft = ft;
		this.tt = tt;
		this.pt = pt;
		this.tID = tID;
	}

	@Override
	public void run() {
		try {
			if (ft != null) {
				ft.join();
			}
			if (tt != null) {
				tt.join();
			}
			if (pt != null) {
				pt.join();
			}
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		Message m = mHandler.obtainMessage();
		Bundle b = new Bundle();
		b.putInt("tID", tID);
		m.setData(b);
		mHandler.sendMessage(m);
	}
}
